import React from 'react';
import {
    ToastAndroid,
    Text,
    View,
    Button,
    Picker,
    AsyncStorage,
    TextInput,
    ScrollView
} from 'react-native';
import { NavigationEvents } from 'react-navigation';
import moment from "moment"
import ModalPerson from "./ModalPerson"
import { getDateList, getTicks, sendVerifyCode, orderTicket } from "../api"
import { Calendar } from 'react-native-calendars';
import Selector from "./Selector"

class HomeScreen extends React.Component {
    static navigationOptions = {
        headerTitle: '订票',
        tabBarLabel: '订票'
    }
    constructor(props) {
        super(props)
        this.state = {
            person: "",
            personModalShow: false,
            persons: undefined,
            personList: [],
            date: "",
            dateList: [],
            ticks: [],
            switchOptions: [],
            tickIndex: 0,
            verifyCode: "",
            loading: false,
            markedDates: {}
        }
    }
    getPerson = async () => {
        try {
            let persons = await AsyncStorage.getItem("persons")
            let person = await AsyncStorage.getItem("person")
            if (persons) {
                persons = JSON.parse(persons)
                personList = []
                for (let key in persons) {
                    personList.push({
                        name: key,
                        phone: persons[key]["phone"],
                        idcard: persons[key]["idcard"]
                    })
                }
            }
            else {
                personList = []
            }

            this.setState({ personList, persons, person: person ? person : "" })

        }
        catch (e) {
            console.log(e)
        }
    }
    getDateList = async () => {
        try {
            let dateList = await getDateList()
            if (dateList.length > 0) {
                await this.getTicks(dateList[0].date)
            }
            this.setState({
                dateList,
                date: dateList[0].date,
                markedDates: {
                    [moment(dateList[0].date).format("YYYY-MM-DD")]: { selected: true }
                }
            })
        }
        catch (e) {
            this.setState({ dateList: [], date: "", markedDates: {} })
        }
    }
    getTicks = async (itemValue) => {
        if (itemValue) {
            let ticks = await getTicks(itemValue)
            this.setState({
                ticks,
                switchOptions: ticks.map((o, index) => {
                    return {
                        value: index,
                        label: `${o.begin}~${o.end} ${o.left}票`
                    }
                }),
                tickIndex: 0
            })
        }
        else {
            this.setState({
                ticks: [],
                switchOptions: [],
                tickIndex: 0
            })
        }
    }
    getData = async () => {
        this.setState({ loading: true })
        try {
            await this.getDateList()
        }
        catch (e) {
        }
        this.setState({ loading: false })
    }
    sendVerifyCode = async () => {
        //{ mobile, actDate, itemId, groundId, startTime, endTime, identityCode, type = 0 }
        return await sendVerifyCode({
            mobile: this.state.persons[this.state.person].phone,
            actDate: this.state.date,
            itemId: 30,
            groundId: this.state.ticks[this.state.tickIndex].site,
            startTime: this.state.ticks[this.state.tickIndex].begin,
            endTime: this.state.ticks[this.state.tickIndex].end,
            identityCode: this.state.persons[this.state.person].idcard,
            type: 0
        })
    }
    orderTicket = async () => {
        return await orderTicket({
            ["orderTicket.mobile"]: this.state.persons[this.state.person].phone,
            ["ticketDetial.actDate"]: this.state.date,
            ["orderTicket.itemId"]: 30,
            ["orderTicket.itemName"]: "游泳",
            ["orderTicket.username"]: this.state.person,
            ["ticketDetial.groundId"]: this.state.ticks[this.state.tickIndex].site,
            ["ticketDetial.groundName"]: this.state.ticks[this.state.tickIndex].siteName,
            ["ticketDetial.startTime"]: this.state.ticks[this.state.tickIndex].begin,
            ["ticketDetial.endTime"]: this.state.ticks[this.state.tickIndex].end,
            ["orderTicket.identityCode"]: this.state.persons[this.state.person].idcard,
            ["orderTicket.mobileCheckCode"]: this.state.verifyCode
        })
    }
    render() {
        return (
            <ScrollView>
                <NavigationEvents
                    onDidFocus={payload => {
                        this.getPerson()
                        this.getData()
                    }}
                />
                <Calendar
                    // Initially visible month. Default = Date()
                    current={this.state.date ? new Date(this.state.date) : ""}
                    // Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined
                    minDate={this.state.dateList.length > 0 ? new Date(this.state.dateList[0].date) : ""}
                    // Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined
                    maxDate={this.state.dateList.length > 0 ? new Date(this.state.dateList[this.state.dateList.length - 1].date) : ""}
                    // Handler which gets executed on day press. Default = undefined
                    onDayPress={(day) => {
                        let date = moment(day.timestamp).format("YYYY/MM/DD")
                        this.setState({
                            date,
                            markedDates: {
                                [day.dateString]: { selected: true }
                            }
                        })
                        this.getTicks(date)
                    }}
                    markedDates={this.state.markedDates}
                />
                <Selector
                    data={this.state.switchOptions}
                    index={this.state.tickIndex}
                    press={(index) => {
                        this.setState({
                            tickIndex: index
                        })
                    }}
                ></Selector>
                <ModalPerson show={this.state.personModalShow} userInfo={this.state.person ? { name: this.state.person, ...this.state.persons[this.state.person] } : undefined} close={() => {
                    this.setState({ personModalShow: false })
                    this.getPerson()
                }}></ModalPerson>
                <View style={{ flexDirection: "row", justifyContent: 'center', alignItems: 'center' }}>
                    <Text>人员</Text>
                    <Picker
                        selectedValue={this.state.person}
                        style={{ flex: 1 }}
                        onValueChange={(itemValue) => this.setState({ person: itemValue })}>
                        <Picker.Item label="无" value="" />
                        {
                            this.state.personList.map(o =>
                                <Picker.Item key={o.name} label={o.name} value={o.name} />
                            )
                        }
                    </Picker>
                    {this.state.person ? <Button color="green"
                        onPress={() => this.setState({ personModalShow: true })}
                        title="编辑"
                    /> : undefined}
                    <Button
                        onPress={() => this.setState({ personModalShow: true, person: "" })}
                        title="添加人员"
                    />
                </View >
                {
                    this.state.person ?
                        <View style={{ width: "100%" }}>
                            <View style={{ flexDirection: "row", justifyContent: 'flex-start', alignItems: 'flex-start' }}>
                                <Text>身份证:</Text><Text>{this.state.persons[this.state.person].idcard}</Text>
                            </View>
                            <View style={{ flexDirection: "row", justifyContent: 'flex-start', alignItems: 'flex-start' }}>
                                <Text>电话:</Text><Text>{this.state.persons[this.state.person].phone}</Text>
                            </View>
                        </View> : undefined
                }
                {
                    this.state.date && this.state.tickIndex >= 0 && this.state.person ?
                        <View style={{ flexDirection: "row", justifyContent: 'center', alignItems: 'center' }}>
                            <Text>验证码</Text>
                            <TextInput
                                style={{
                                    flex: 1,
                                    borderColor: 'gray',
                                    borderBottomWidth: 1
                                }}
                                onChangeText={(text) => this.setState({ verifyCode: text })}
                                value={this.state.verifyCode}>
                            </TextInput>
                            <Button
                                onPress={() => {
                                    this.sendVerifyCode().then(res => {
                                        ToastAndroid.show(res.message, ToastAndroid.SHORT);
                                    }).catch(e => {
                                        ToastAndroid.show(e.message, ToastAndroid.SHORT);
                                    })
                                }}
                                title="发送验证码"
                            />
                        </View > : undefined
                }
                {
                    this.state.verifyCode ?
                        <View style={{ width: "100%", padding: 32 }}>
                            <Button
                                onPress={() => {
                                    this.orderTicket().then(res => {
                                        this.props.navigation.navigate('Settings');
                                    }).catch(e => {
                                        ToastAndroid.show(e.message, ToastAndroid.SHORT);
                                    })
                                }}
                                title="订票"
                            />
                        </View> : undefined

                }
            </ScrollView >
        );
    }
}

export default HomeScreen